package no.uib.hplims.jobs;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class DatabaseBackup implements Job {
	
	// DB BACKUP PROPERTIES
	
	// EMAIL PROPERTIES
	private static final String SMTP_HOST = ""; 			// Add smtp server here
	private static final String FROM_EMAIL = ""; 		// Add email account to send backup from
	private static final String FROM_EMAIL_PWD = ""; 	// Password
	private static final String TO_EMAIL = FROM_EMAIL;					// Specify where backup file should be sent

	public DatabaseBackup() {

	}

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try {
			String username = "root";
			String password = "qwe1212qwe1212";
			String database = "hplimstest";
			String filename = "backup_" + database + ".sql";

			System.out.println(new Date().toString()
					+ " - Starting backup of database");

			Process runProcess = Runtime.getRuntime().exec(
					"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe -u"
							+ username + " -p" + password + " " + database
							+ " -r\"" + filename);

			if (runProcess.waitFor() == 0) {

				System.out.println(new Date().toString()
						+ " - Backup complete ");

				File f = new File(filename);
				if (f.exists()) {
					System.out.println(new Date().toString()
							+ " - emailing backup");
					
					emailBackupFile(f);
					
					System.out.println(new Date().toString()
							+ " - email backup completed");
				} else {
					System.out.println(new Date().toString()
							+ " - File does not exist: " + filename);
				}
			} else {
				System.out.println("Something went wrong with the backup");
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void emailBackupFile(File f) {
		try {
			// SMTP
			String host = SMTP_HOST;
			// From email
			String from = FROM_EMAIL;
			// Email password to access SMTP
			String pass = FROM_EMAIL_PWD;

			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", pass);
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");

			// Send email to:
			String[] to = { TO_EMAIL };

			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));

			InternetAddress[] toAddress = new InternetAddress[to.length];

			// To get the array of addresses
			for (int i = 0; i < to.length; i++) { // changed from a while loop
				toAddress[i] = new InternetAddress(to[i]);
			}
			System.out.println(Message.RecipientType.TO);

			for (int i = 0; i < toAddress.length; i++) { // changed from a while
															// loop
				message.addRecipient(Message.RecipientType.TO, toAddress[i]);
			}
			message.setSubject("HP LIMS backup");

			// create the message part
			MimeBodyPart messageBodyPart = new MimeBodyPart();

			// fill message
			messageBodyPart.setText("");

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);

			// Part two is attachment: File f
			messageBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(f);
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName(f.getName());
			multipart.addBodyPart(messageBodyPart);

			// Put parts in message
			message.setContent(multipart);

			Transport transport = session.getTransport("smtp");
			transport.connect(host, from, pass);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}
